<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class News extends CI_Controller{
    
    //Mang tham so nhan duoc o moi action
    protected $_arrParam;
    
    // Mang tham so duong dan upload
    protected $_controllerConfig;
    
    public function __construct(){        
        parent::__construct();
        require_once(APPPATH . 'modules/backend/autoload.php');
		$this->load->language('backend');
		$this->smarty->assign('language', $this->lang);
		$this->smarty->assign('message',$this->session->flashdata('message'));
		$this->smarty->assign('error_message',$this->session->flashdata('error_message'));
        
        //khai bao thu muc upload 	
        $this->_controllerConfig  = array('imagesDir'=> FILES_PATH.'/images/');		
		$this->_arrParam['controllerConfig'] = $this->_controllerConfig;
        
        $jqxtheme = array(base_url() . 'library/jqwidgets/styles/jqx.darkblue.css');
        
        $jqueryui = array(base_url() . 'jscripts/jquery-ui/jquery-ui-1.8.21.min.js');
        
        $css_files = array(base_url() . 'jscripts/jqxGrid/styles/jqx.base.css');

        $js_files = array(
                base_url() . 'jscripts/jqxGrid/jqx-all.js',
                base_url() . 'jscripts/tiny_mce/tiny_mce.js',
                base_url() . 'jscripts/tiny_mce/tinymce_config.js'
        );
        
        //$this->smarty->assign('jqueryui', $jqueryui);
        $this->smarty->assign('jqxtheme', $jqxtheme);
        $this->smarty->assign('css_files', $css_files);
        $this->smarty->assign('js_files', $js_files);
        
        require_once(APPPATH . 'modules/backend/denied.php');
    }
    
    public function category(){   
        $this->smarty->assign('title','Admin Panel - Quản lý tin tức : Danh mục tin');
        $this->smarty->assign('heading','QUẢN LÝ TIN TỨC : DANH MỤC TIN');
        $jqxgrid_init = $this->smarty->get_contents('backend/js/jqx_news_category');
        $js_text = array($jqxgrid_init);
        $this->smarty->assign('js_text', $js_text);
        
        $this->smarty->view('backend/news/category', 'grid');
        $this->smarty->display('backend/admin');
        
        $user = $this->login_manager->get_user();
        $aParamAdminLog=array(
                        'username'   => $user[0]->name,
                        'customerID' => $user[0]->customerID,
                        'email'      => $user[0]->email,
                        'lastLogin'  => date("Y-m-d H:i:s"),
                        'logAction'  => "Quản lý tin tức : Danh mục tin",
                        'ip'         => $_SERVER['REMOTE_ADDR'],
                        'uID'        => $user[0]->uID
                        );
        $log = $this->db_user_model->insertUserAdminLog($aParamAdminLog);
    }
    
    public function data_json_category(){
        if(IS_AJAX){
            $user = $this->login_manager->get_user();
            $this->db_news_model->actionCategory($this->_arrParam,$user[0]);
            
            if(isset($this->_arrParam['update'])){
                $userlog = $this->db_user_model->getNewsCategory($this->_arrParam['id']);
                foreach($userlog as $value){
                    $catName = $value->name;
                }
                
                $aParamAdminLog=array(
                            'username'   => $user[0]->name,
                            'customerID' => $user[0]->customerID,
                            'email'      => $user[0]->email,
                            'lastLogin'  => date("Y-m-d H:i:s"),
                            'logAction'  => "Quản lý tin tức :  Danh mục tin : ".$catName. " : Status = ".$this->_arrParam['status'],
                            'ip'         => $_SERVER['REMOTE_ADDR'],
                            'uID'        => $user[0]->uID
                            );
                $log = $this->db_user_model->insertUserAdminLog($aParamAdminLog);
            }
        }
    }
    
    public function newsList(){   
        $this->smarty->assign('title','Admin Panel - Quản lý tin tức : List Tin');
        $this->smarty->assign('heading','QUẢN LÝ TIN TỨC : DANH SÁCH TIN');
        $jqxgrid_init = $this->smarty->get_contents('backend/js/jqx_news_list');
        $js_text = array($jqxgrid_init);
        $this->smarty->assign('js_text', $js_text);
        
        $this->smarty->view('backend/news/newslist', 'grid');
        $this->smarty->display('backend/admin');
        
        $user = $this->login_manager->get_user();
        $aParamAdminLog=array(
                        'username'   => $user[0]->name,
                        'customerID' => $user[0]->customerID,
                        'email'      => $user[0]->email,
                        'lastLogin'  => date("Y-m-d H:i:s"),
                        'logAction'  => "Quản lý tin tức : Danh sách tin",
                        'ip'         => $_SERVER['REMOTE_ADDR'],
                        'uID'        => $user[0]->uID
                        );
        $log = $this->db_user_model->insertUserAdminLog($aParamAdminLog);
    }
    
    public function data_json_newslist(){
        if(IS_AJAX){
            $user = $this->login_manager->get_user();
            $this->db_news_model->actionNews($this->_arrParam);
            
            if(isset($this->_arrParam['update'])){
                $userlog = $this->db_user_model->getNews($this->_arrParam['id']);
                foreach($userlog as $value){
                    $catName = $value->title;
                }
                
                $aParamAdminLog=array(
                            'username'   => $user[0]->name,
                            'customerID' => $user[0]->customerID,
                            'email'      => $user[0]->email,
                            'lastLogin'  => date("Y-m-d H:i:s"),
                            'logAction'  => "Quản lý tin tức :  Danh sách tin : ".$catName. " : Status = ".$this->_arrParam['status'],
                            'ip'         => $_SERVER['REMOTE_ADDR'],
                            'uID'        => $user[0]->uID
                            );
                $log = $this->db_user_model->insertUserAdminLog($aParamAdminLog);
            }
        }
    }
    
    function select($str){ // Validation Select
        if($str == 0){
            $this->form_validation->set_message('select', 'Trường %s là bắt buộc.');
			return FALSE;
        }else{
            return TRUE;
        }
    } 
    
    public function check_title_insert(){ 
        if(IS_AJAX){
            $result = $this->db_news_model->check_title_exist($this->_arrParam, array("task" => "check-title-insert"));
            if($result){
                return true;
            }else{
                echo "<div class='error-form'>Tiêu đề bạn nhập đã tồn tại.</div>";
            }
        }
    }
    
    public function check_title_update(){ 
        if(IS_AJAX){
            $result = $this->db_news_model->check_title_exist($this->_arrParam, array("task" => "check-title-update"));
            if($result){
                return true;
            }else{
                echo "<div class='error-form'>Tiêu đề bạn nhập đã tồn tại.</div>";
            }
        }
    }
    
    public function newsInsert(){
        $this->load->helper('form');
        $this->load->library('form_validation');
        
        /** Validator Form  */
        $this->form_validation->set_error_delimiters('<div class="error-form">','</div>'); 
        $this->form_validation->set_rules('title','Tiêu đề ','required');
        $this->form_validation->set_rules('description','Mô tả ','required');
        $this->form_validation->set_rules('category_id','Danh mục ','require|callback_select');
        $this->form_validation->set_rules('active','Options ','required');
        $this->form_validation->set_rules('code','Mã ','required');
        $this->form_validation->set_rules('keyword','Keyword ','required');
        $this->form_validation->set_rules('content_news','Nội dung ','required');
        if (empty($_FILES['image']['name'])){
            $this->form_validation->set_rules('image','Hình ảnh ','required');
        }
                
        if($this->form_validation->run() == FALSE){ 
            //echo "<script>alert('Error')</script>";
            $this->smarty->assign('title','Admin Panel - Quản lý tin tức : Thêm tin mới Tin');
            $this->smarty->assign('heading','QUẢN LÝ TIN TỨC : THÊM TIN MỚI');
            
            $CategoryID = $this->db_news_model->getCategoryID();
            $this->smarty->assign("categoryID", $CategoryID);
            
            $this->smarty->view('backend/news/newsinsert', 'grid');
            $this->smarty->display('backend/admin');

        }else{
            // Success
            $uploadDir = $this->_controllerConfig['imagesDir'];
            $config['upload_path'] = $uploadDir.'full_images';
            $config['allowed_types'] = 'gif|jpg|png|jpeg';
            $file_name = time().$_FILES['image']['name'];
            $config['file_name'] = $file_name;
            $this->load->library('upload', $config);
            
            if($this->upload->do_upload('image')){
                /** Upload image */
                $file_success = $this->upload->data();
                
                $config = array("source_image" => $file_success['full_path'],
                                "new_image" => $uploadDir."thumbs",
                                "maintain_ration" => true,
                                "width" => '200',
                                "height" => "150");
                $this->load->library("image_lib",$config);
                $this->image_lib->resize();
                
                $user = $this->login_manager->get_user();
                
                /** insert params */
                $this->db_news_model->saveItem($this->_arrParam, array('task'=>'admin-add'), $user[0], $file_success['file_name']);
                
                /** insert adminlog */
                $aParamAdminLog=array(
                                'username'   => $user[0]->name,
                                'customerID' => $user[0]->customerID,
                                'email'      => $user[0]->email,
                                'lastLogin'  => date("Y-m-d H:i:s"),
                                'logAction'  => "Quản lý tin tức : Thêm mới tin : ".$this->_arrParam['title'],
                                'ip'         => $_SERVER['REMOTE_ADDR'],
                                'uID'        => $user[0]->uID
                                );
                $log = $this->db_user_model->insertUserAdminLog($aParamAdminLog);
                
                //redirect(base_url('admin/news/newsList', 'refresh'));
                echo "<script>location.href='".base_url('admin/news/newsList')."'</script>";         
            }           
        }
    }
    
    public function newsUpdate(){
        $this->load->helper('form');
                
        $this->smarty->assign('title','Admin Panel - Quản lý tin tức : Sửa Tin');
        $this->smarty->assign('heading','QUẢN LÝ TIN TỨC : SỬA TIN');
        
        $CategoryID = $this->db_news_model->getCategoryID();
        $this->smarty->assign("categoryID", $CategoryID);
        
        $newsResult = $this->db_news_model->getWhereNews($this->_arrParam);
        $this->smarty->assign("newsResult", $newsResult);
        
        $this->smarty->view('backend/news/newsupdate', 'grid');
        $this->smarty->display('backend/admin');
        
        if(isset($this->_arrParam['submit'])){
            
            $uploadDir = $this->_controllerConfig['imagesDir'];
            $config['upload_path'] = $uploadDir.'full_images';
            $config['allowed_types'] = 'gif|jpg|png|jpeg';
            $file_name = time().$_FILES['image']['name'];
            $config['file_name'] = $file_name;
            $this->load->library('upload', $config);
            
            $images = null;
            
            if($this->upload->do_upload('image')){

                $file_success = $this->upload->data();
                
                $config = array("source_image" => $file_success['full_path'],
                                "new_image" => $uploadDir."thumbs",
                                "maintain_ration" => true,
                                "width" => '200',
                                "height" => "150");
                $this->load->library("image_lib",$config);
                $this->image_lib->resize();
                
                $images = $file_success['file_name'];
                
                /** Remove hình cũ */
                $Result = $this->db_news_model->getWhere($this->_arrParam);
                foreach($Result as $image){
                    @unlink($uploadDir . 'full_images/' . $image->image);
                    @unlink($uploadDir . 'thumbs/' . $image->image);						
                }
                
            }else{
                $images = $this->_arrParam['image_temp'];
            }    
            $user = $this->login_manager->get_user();
            
            /** Update params */
            $this->db_news_model->saveItem($this->_arrParam, array('task'=>'admin-edit'), $user[0], $images);
            
            /** insert adminlog */
            $aParamAdminLog=array(
                            'username'   => $user[0]->name,
                            'customerID' => $user[0]->customerID,
                            'email'      => $user[0]->email,
                            'lastLogin'  => date("Y-m-d H:i:s"),
                            'logAction'  => "Quản lý tin tức : Sửa tin : ".$this->_arrParam['title'],
                            'ip'         => $_SERVER['REMOTE_ADDR'],
                            'uID'        => $user[0]->uID
                            );
            $log = $this->db_user_model->insertUserAdminLog($aParamAdminLog);

            echo "<script>location.href='".base_url('admin/news/newsList')."'</script>";         
        }
    }
    
    
/**
 * public function menuNewCategory(){
 *         echo '<meta http-equiv="content-type" content="text/html;charset=utf-8" />';
 *         $categoryData = array();
 *         $result = $this->db_news_model->getNewCategory();
 *         foreach($result as $row){
 *             $categoryData[$row->parents][$row->id] = $row->name;
 *         }
 *         echo getCategory($categoryData);
 *         
 *         $Menu = $this->db_news_model->Menu();
 *         echo "<select>";
 *         foreach($Menu as $row){
 *             echo "<option value='".$row['id']."'>".$row['name']."</option>";
 *         }
 *         echo "</select>";
 *     }
 */
}

/* End of file news.php */
/* Location: ./system/application/controllers/backend/news.php */